#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include "tcp_client.h"
#include "hal.h"
#include "infra_types.h"

void my_tcp_client_state_notify_cb(tcp_client_t *pclient, tc_state_t state)
{
    printf("my_tcp_client_state_notify_cb state = %d\n", state);
}

void my_tcp_client_data_recv_cb(tcp_client_t *pclient, int packet_type, unsigned char *payload, uint32_t length, void *user_data)
{
    printf("packet_type = %d\n", packet_type);
    printf("payload length = %d\n", length);
    //printf("payload:[%.02X][%.02X][%.02X][%.02X]", payload[0], payload[1], payload[2], payload[3]);

    if(packet_type == 1){
        printf("recv music packet\n");

        FILE *file = fopen("break-beat.wav", "wb"); // 以二进制写模式打开文件
        if (file == NULL) {
            printf("Error opening file\n");
        }

        // 写入缓冲区数据
        size_t written = fwrite(payload, 1, length, file);
        if (written != length) {
            printf("Error writing to file, writtn=%ld\n", written);
            fclose(file);
        }

        printf("file written=%ld\n", written);

        if(ferror(file)){
            printf("Error writing to file\n");
        }

        fflush(file);

        // 关闭文件
        fclose(file);
    }

    
}



int main(void)
{
    int rc, cnt = 0, len;
    tcp_client_t *pclient = NULL;
    char test_send_buf[128] = {0};
    
    printf("Hello, World!\n");

    pclient = tcp_client_new("0.0.0.0", 9010);
    if (NULL == pclient) {
        printf("tcp_client_new failed\n");
        return -1;
    }

    tcp_client_set_state_notify_cb(pclient, my_tcp_client_state_notify_cb);
    tcp_client_set_data_recv_cb(pclient, my_tcp_client_data_recv_cb, NULL);


    do{
        rc = tcp_client_connect(pclient);
        HAL_SleepMs(1000);
    } while(rc != 0);

    test_send_buf[0] = 0x00;
    test_send_buf[1] = 0x01;
    test_send_buf[2] = 0x00;
    test_send_buf[3] = 0x00;
    test_send_buf[4] = 0x00;
    test_send_buf[5] = 0x01;
    test_send_buf[6] = 0x00;


    while(1){
        tcp_client_yield(pclient, 1000);

        printf("cnt = %d\n", cnt++);
        if(cnt == 10){
            HAL_Printf("req music packet\n");
            tcp_client_send(pclient, test_send_buf, 7);
        }
    }

    return 0;
}